/**
 * Created by Toma on 2016/9/14.
 */

"use strict";

// 存入历史
var state = {
  push: function (title, query) {
    document.title = title;
    history.pushState({title: title}, title, '?link=' + query);
  },
  replace: function (title, query) {
    document.title = title;
    history.replaceState({title: title}, title, '?link=' + query);
  },
  pop: function (callback) {
    window.addEventListener('popstate', function () {
      callback();
    });
  }
};

$('.link').on('click', function (e) {
  e.preventDefault();
  var $this = $(this);
  var query = $this.data('link')
  state.push($this.text(), query);
  hashTrigger(query);
});

function hashTrigger(query) {
  if (!query) {
    // todo 判断search 是否合法
    var seh = window.location.search;
    seh ? function () {
      var que = seh.replace(/\?link=/, '');
      state.replace($('.link[data-link="' + que + '"]').text(), que);
      ajax(que);
    }() : $('.link').eq(0).trigger('click');
  } else {
    ajax(query);
  }
}

function ajax(query) {
  $.get('data/' + query + '.html?ver0.1', function (data) {
    $('.J_box').html($(data).html());
  }, 'html');
}

state.pop(hashTrigger);
hashTrigger();